<script lang="ts" setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, FormInstance, FormRules, ElTree } from 'element-plus'
import wsjzglService from '@/api/wsjzgl'
import { useMainStore } from '@/store/main'
import TreeUtilDTO from '@/utils/tree'
import { useRoute } from 'vue-router'

const route = useRoute()
const store = useMainStore()
const emit = defineEmits(['refresh'])

const isLoading = ref(false)
const ruleFormRef = ref<FormInstance>()

//打开窗口

const dialogVisible = ref(false)
const nodeData = ref()

const openDialog = (data: any) => {
  queryAjml()
  nodeData.value = data
  dialogVisible.value = true
}

const firtsNode = ref<any>()
const form = ref({
  gjz: '',
})

const defaultProps = {
  children: 'children',
  label: 'mc',
}

const treeData = ref<any[]>([])
const queryAjml = () => {
  const params = {
    ajbh: route.query.ajbh as unknown as string,
    mlmc: '',
    mlxslx: '0',
  }
  wsjzglService
    .queryAjmls(params)
    .then((res) => {
      let filteredData = TreeUtilDTO.getTreeData(res.data, 'bh', 'fbh')
      filteredData = filteredData.filter((item: any) => {
        if (item.children && item.children.length > 0) {
          item.children.forEach((data1: any) => {
            data1['children'] = [
              {
                ...data1,
                dm: 'gd0010001',
                lbbm: 'gd001',
                lbmc: '文件类型',
                mc: '正文',
                sgly: '0',
                cj: '3',
              },
              {
                ...data1,
                dm: 'gd0010002',
                lbbm: 'gd001',
                lbmc: '文件类型',
                mc: '签发',
                sgly: '0',
                cj: '3',
              },
              {
                ...data1,
                dm: 'gd0010003',
                lbbm: 'gd001',
                lbmc: '文件类型',
                mc: '底稿',
                sgly: '0',
                cj: '3',
              },
            ]
          })
        }
        // return item.mc !== '待编目材料'
        return item
      })

      treeData.value = filteredData
      treeData.value?.forEach((data: any) => {
        if (data.children && data.children.length > 0) {
          data.children = data.children.sort((a: any, b: any) => a.mlsxh - b.mlsxh)
          data.children.forEach((data1: any) => {
            if (data.bh === data1.fbh && data1.mc === '正卷') {
              data1['zfj'] = '正卷'
            }
            if (data.bh === data1.fbh && data1.mc === '副卷') {
              data1['zfj'] = '副卷'
            }
          })
        }
      })
      if (treeData.value.length) {
        firtsNode.value = null
        // 递归选择第一个
        getFirstNode(treeData.value)
        if (firtsNode.value) {
          handleCheckNode(firtsNode.value)
        }
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

const getFirstNode = (arr: any[]) => {
  if (firtsNode.value) return
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].children && arr[i].children.length > 0) {
      getFirstNode(arr[i].children)
    } else {
      firtsNode.value = arr[i]
    }
  }
}

const treeRef = ref<InstanceType<typeof ElTree>>()
const handleCheckNode = (node: any) => {
  treeNodeClick(node)
  nextTick(() => {
    treeRef.value!.setCurrentKey(node.bh)
  })
}

const treeNodeData = ref<any>()
// 树节点点击
const treeNodeClick = (data: any) => {
  treeNodeData.value = data
}
const save = () => {
  if (!treeNodeData.value.dm) {
    return ElMessage({
      type: 'warning',
      message: '请选择调整到具体的位置',
    })
  }

  const params = {
    ajbh: treeNodeData.value.ajbh,
    mlbh: store.nodeTreeData?.bh,
    tzhmlbh: treeNodeData.value.bh,
    tzhwjlxdm: treeNodeData.value.dm,
    tzhwjlxmc: treeNodeData.value.mc,
    wjbhList: nodeData.value.map((item: any) => item.wjbh),
  }
  isLoading.value = true
  wsjzglService
    .updateWjwz(params, route.query.ajbh as string)
    .then(() => {
      ElMessage({
        type: 'success',
        message: '保存成功',
      })
      closeDialog()
      emit('refresh', params)
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      isLoading.value = false
    })
}

// 文字过滤
const filterTree = () => {
  treeRef.value?.filter(form.value.gjz)
}

// 筛选
const filterNode = (value: string, data: any, node: any) => {
  if (!value) return true
  // 文字过滤
  let parentNode = node.parent
  let labels = [node.label]
  let level = 1 // 层级
  while (level < node.level) {
    labels = [...labels, parentNode.label] // 当前node名字，父级node的名字
    parentNode = parentNode.parent
    level++
  }
  return labels.some((d) => d.indexOf(value) !== -1)
}

/*
 * 关闭弹框
 */
const closeDialog = () => {
  dialogVisible.value = false
}

defineExpose({ openDialog })
</script>

<template>
  <el-dialog
    v-model="dialogVisible"
    title="位置调整"
    width="600px"
    :close-on-click-modal="false"
    :before-close="closeDialog"
  >
    <div class="dialog-content">
      <div class="wztz-header">
        <el-input v-model="form.gjz" placeholder="请输入关键字查询" @change="filterTree"></el-input>
        <el-button type="primary" @click="filterTree">查询</el-button>
      </div>
      <el-tree
        ref="treeRef"
        style="max-width: 600px"
        :data="treeData"
        node-key="bh"
        highlight-current
        :expand-on-click-node="false"
        :props="defaultProps"
        @node-click="treeNodeClick"
        :filter-node-method="filterNode"
      >
        <template #default="{ data }">
          <div class="custom-tree-node">
            <!-- <el-icon v-if="data.fbh"> <FolderOpened /></el-icon> -->
            <!-- <img v-if="!data.fbh" src="/src/assets/images/file-icon.png" alt="" /> -->
            <img
              v-if="data.mc === '正卷' || data.mc === '副卷'"
              src="/src/assets/images/dbm.png"
              alt=""
            />
            <img v-if="data.mc === '待编目材料'" src="/src/assets/images/juan.png" alt="" />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && (data.sfyy === 'N' || !data.sfyy)"
              style="margin-right: 5px"
              src="/src/assets/images/xswjwyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && data.sfdzajml === 'Y' && data.sfyy === 'Y'"
              style="margin-right: 5px"
              src="/src/assets/images/xsxwjyyz.png"
              alt=""
            />
            <img
              v-if="data.cj === '2' && (data.sfzzajml === 'Y' || !data.sfzzajml)"
              src="/src/assets/images/xxwj.png"
              alt=""
            />
            <span :class="data.cj === '2' ? 'over-title' : ''" :title="data.mc"
              >&nbsp;{{ data.mc }}&nbsp;</span
            >
          </div>
        </template>
      </el-tree>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save" :loading="isLoading">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.dialog-content {
  width: 100%;
  height: 600px;
  display: flex;
  flex-direction: column;
  .el-tree {
    height: calc(100% - 32px);
    overflow: auto;
  }
}

.custom-tree-node {
  width: calc(100% - 40px);
  display: flex;
  align-items: center;
  .over-title {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
  }
}

.wztz-header {
  display: flex;
  .el-input {
    width: calc(100% - 300px);
  }
  .el-button {
    margin-left: 10px;
  }
}
</style>
